package com.song.guli.service.oss.controller;

import com.song.guli.common.base.result.R;
import com.song.guli.common.base.result.ResultCodeEnum;
import com.song.guli.common.base.util.ExceptionUtils;
import com.song.guli.service.base.exception.GuliException;
import com.song.guli.service.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author 宋超
 * HP - the login name of the current user.
 * 2021/4/2 - the current system date.
 * 18:12 - the current system time.
 */
@Api("阿里云文件管理")
@RestController
//@CrossOrigin
@RequestMapping("/admin/oss/file")
@Slf4j
public class admin {
    @Autowired
    private FileService fileService;

    /**
     * 文件上传
     * @param file
     * @param module
     * @return
     * @throws IOException
     */
    @ApiOperation("文件上传")
    @PostMapping("upload")
    public R upload(@ApiParam(value = "文件", required = true)
                        @RequestParam("file") MultipartFile file,
                    @ApiParam(value = "模块", required = true)
                    @RequestParam("module") String module) {
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.uploadfile(inputStream, module, originalFilename);

            return R.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (Exception e) {
            log.error(ExceptionUtils.getMessage(e));
            throw new GuliException(ResultCodeEnum.FILE_UPLOAD_ERROR);
        }
    }

    @ApiOperation(value = "删除文件")
    @DeleteMapping("remove")
    public R removefile( @ApiParam(value = "要删除的文件路径", required = true)
                             @RequestBody String url){
        fileService.removefile(url);
        return R.ok().message("删除成功");
    }

    @ApiOperation(value = "测试")
    @GetMapping("test")
    public R test() {
        log.info("oss test被调用");
        return R.ok();
    }
}
